package com.faxsun.validation;

import org.broadleafcommerce.core.web.checkout.model.ShippingInfoForm;
import org.broadleafcommerce.core.web.checkout.validator.ShippingInfoFormValidator;
import org.broadleafcommerce.profile.core.domain.Address;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;

import com.faxsun.core.tool.IDCardValidator;
import com.faxsun.core.web.checkout.model.FSShippingInfoForm;
import com.faxsun.profile.core.domain.FSAddress;
import com.faxsun.profile.core.domain.FSReceiver;

/**
 * 身份证信息验证器
 * 
 * @author zhaoteng.song@faxsun.com
 *
 */
public class FSShippingInfoFormValidator extends ShippingInfoFormValidator {

	@SuppressWarnings("rawtypes")
	public boolean supports(Class clazz) {
		return clazz.equals(FSShippingInfoForm.class);
	}

	@Override
	public void validate(Object obj, Errors errors) {
		ShippingInfoForm shippingInfoForm = (ShippingInfoForm) obj;

		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address.addressLine1", "addressLine1.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address.state", "state.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address.city", "city.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address.postalCode", "postalCode.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address.firstName", "firstName.required");

		Address address = shippingInfoForm.getAddress();
		if (address.getCountry() == null) {
			errors.rejectValue("address.country", "country.required", null, null);
		}

		// ValidationUtils.rejectIfEmptyOrWhitespace(errors,
		// "fulfillmentOptionId", "fulfillmentOptionId.required");

		FSAddress fsAddress = (FSAddress) address;
		FSShippingInfoForm shippingForm = (FSShippingInfoForm) obj;
		FSReceiver receiver = fsAddress.getReceiver();

		if (shippingForm.getIsIdCardRequired()) {
			// id card is required

			String idCardNo = receiver.getIdCard();
			if (idCardNo == null || idCardNo.isEmpty()) {
				errors.rejectValue("address.receiver.idCard", "idCard.required");
			} else {
				String isValidate = IDCardValidator.IDCardValidate(idCardNo);
				if (!isValidate.isEmpty()) {
					errors.rejectValue("address.receiver.idCard", "idCard.invalidate");
				}
			}
		}
	}
}
